package middleware

import (
	"encoding/json"
	"im/global"
	"im/model"
	"im/model/response"

	"github.com/gin-gonic/gin"
)

func JWTAuth() gin.HandlerFunc {

	return func(c *gin.Context) {
		token := c.GetHeader(global.TOKEN_HEADER)
		if token == "" {
			response.FailWithMessage("未登录或非法访问", c)
			c.Abort() // 登录失败则禁止访问
			return
		}

		// 判断redis
		key := global.TOKEN_KEY_PROFIX + token
		var claims *model.TokenClaims
		if value, err := global.RD.Get(global.CTX, key).Result(); err != nil {
			response.FailWithMessage("无效token", c)
			// response.Result(global.ExpireToken, fiber.Map{"reload": true}, err.Error(), c)
			c.Abort()
		} else {
			json.Unmarshal([]byte(value), claims)
			c.Set("claims", claims)
			// UUID 校验合法性
			c.Next()
		}

		/**
		if claims.ID == 0 {

			j := model.NewJWT()
			// parseToken 解析token包含的信息
			var err error
			claims, err = j.ParseToken(token)
			if err != nil {
				response.FailWithMessage("token解析失败", c)
				// response.Result(global.ExpireToken, fiber.Map{"reload": true}, err.Error(), c)
				c.Abort()
				return
			} else {
				c.Set("claims", claims)
				// UUID 校验合法性
				c.Next()
			}
		}
		*/

	}
}
